package com.bw.kf.playvideo

import com.example.common.mvi.NetworkResult
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.delay
import java.text.SimpleDateFormat
import java.util.*
import kotlin.random.Random

class CommentRepository {
    
    // 本地评论存储
    private val localComments = mutableMapOf<String, MutableList<CommentEntityItem>>()
    private var commentIdCounter = 1000
    private val dateFormat = SimpleDateFormat("MM-dd HH:mm", Locale.getDefault())
    
    /**
     * 获取评论列表（本地数据）
     */
    fun getComments(datatype: Int, itemid: String): Flow<NetworkResult<CommentEntity>> {
        return kotlinx.coroutines.flow.flow {
            try {
                emit(NetworkResult.Loading)
                delay(300) // 模拟加载时间
                
                val comments = localComments[itemid] ?: mutableListOf()
                
                // 如果是第一次访问，创建一些示例评论
                if (comments.isEmpty()) {
                    initializeSampleComments(itemid)
                }
                
                val sortedComments = CommentUtils.sortComments(
                    localComments[itemid] ?: emptyList(), 
                    CommentSortType.TIME_DESC
                )
                
                val entity = CommentEntity(
                    code = 200,
                    msg = "获取成功",
                    data = sortedComments
                )
                
                emit(NetworkResult.Success(entity))
            } catch (e: Exception) {
                emit(NetworkResult.Error(e))
            }
        }
    }

    /**
     * 发送评论（本地处理，带内容过滤）
     */
    fun sendComment(datatype: Int, itemid: String, content: String): Flow<NetworkResult<SendCommentResponse>> {
        return kotlinx.coroutines.flow.flow {
            try {
                emit(NetworkResult.Loading)
                delay(200) // 模拟发送延迟
                
                // 先进行内容过滤检查
                val filterResult = CommentFilter.checkContent(content)
                if (!filterResult.isValid) {
                    emit(NetworkResult.Error(Exception(filterResult.message)))
                    return@flow
                }
                
                // 创建新评论
                val newComment = CommentEntityItem(
                    id = ++commentIdCounter,
                    datatype = datatype,
                    itemid = itemid,
                    content = content,
                    userid = UserManager.getUserId(),
                    nickname = UserManager.getUserName(),
                    userlogo = UserManager.getUserAvatar(),
                    createtime = dateFormat.format(Date()),
                    replytotal = 0,
                    agreenum = 0,
                    replyList = mutableListOf(),
                    parentId = null,
                    replyToUserId = null,
                    replyToUserName = null,
                    isLiked = false
                )
                
                // 添加到本地存储
                val comments = localComments.getOrPut(itemid) { mutableListOf() }
                comments.add(0, newComment) // 新评论添加到顶部
                
                val response = SendCommentResponse(
                    code = 200,
                    msg = "评论发送成功",
                    data = newComment
                )
                
                emit(NetworkResult.Success(response))
                
            } catch (e: Exception) {
                emit(NetworkResult.Error(e))
            }
        }
    }
    
    /**
     * 发送回复（本地处理，带内容过滤）
     */
    fun sendReply(
        datatype: Int, 
        itemid: String, 
        content: String, 
        parentId: Int,
        replyToUserId: Int? = null,
        replyToUserName: String? = null
    ): Flow<NetworkResult<SendCommentResponse>> {
        return kotlinx.coroutines.flow.flow {
            try {
                emit(NetworkResult.Loading)
                delay(200) // 模拟发送延迟
                
                // 先进行内容过滤检查
                val filterResult = CommentFilter.checkContent(content)
                if (!filterResult.isValid) {
                    emit(NetworkResult.Error(Exception(filterResult.message)))
                    return@flow
                }
                
                // 创建新回复
                val newReply = CommentEntityItem(
                    id = ++commentIdCounter,
                    datatype = datatype,
                    itemid = itemid,
                    content = content,
                    userid = UserManager.getUserId(),
                    nickname = UserManager.getUserName(),
                    userlogo = UserManager.getUserAvatar(),
                    createtime = dateFormat.format(Date()),
                    replytotal = 0,
                    agreenum = 0,
                    replyList = mutableListOf(),
                    parentId = parentId,
                    replyToUserId = replyToUserId,
                    replyToUserName = replyToUserName,
                    isLiked = false
                )
                
                // 找到父评论并添加回复
                val comments = localComments[itemid] ?: mutableListOf()
                val parentComment = findCommentById(comments, parentId)
                
                if (parentComment != null) {
                    if (parentComment.replyList == null) {
                        parentComment.replyList = mutableListOf()
                    }
                    parentComment.replyList!!.add(0, newReply) // 新回复添加到顶部
                    parentComment.replytotal++
                    
                    val response = SendCommentResponse(
                        code = 200,
                        msg = "回复发送成功",
                        data = newReply
                    )
                    
                    emit(NetworkResult.Success(response))
                } else {
                    emit(NetworkResult.Error(Exception("找不到父评论")))
                }
                
            } catch (e: Exception) {
                emit(NetworkResult.Error(e))
            }
        }
    }
    
    /**
     * 点赞评论（本地处理）
     */
    fun likeComment(commentId: Int): Flow<NetworkResult<SendCommentResponse>> {
        return kotlinx.coroutines.flow.flow {
            try {
                emit(NetworkResult.Loading)
                delay(100) // 模拟网络延迟
                
                // 在所有视频的评论中查找
                var targetComment: CommentEntityItem? = null
                for (comments in localComments.values) {
                    targetComment = findCommentById(comments, commentId)
                    if (targetComment != null) break
                }
                
                if (targetComment != null) {
                    // 切换点赞状态
                    targetComment.isLiked = !targetComment.isLiked
                    targetComment.agreenum += if (targetComment.isLiked) 1 else -1
                    
                    val response = SendCommentResponse(
                        code = 200,
                        msg = if (targetComment.isLiked) "点赞成功" else "取消点赞",
                        data = targetComment
                    )
                    
                    emit(NetworkResult.Success(response))
                } else {
                    emit(NetworkResult.Error(Exception("找不到评论")))
                }
                
            } catch (e: Exception) {
                emit(NetworkResult.Error(e))
            }
        }
    }
    
    /**
     * 初始化示例评论数据
     */
    private fun initializeSampleComments(itemid: String) {
        val sampleComments = mutableListOf<CommentEntityItem>()
        
        // 创建一些示例评论
        val comment1 = CommentEntityItem(
            id = ++commentIdCounter,
            datatype = 0,
            itemid = itemid,
            content = "这个视频真不错，学到了很多！",
            userid = 1001,
            nickname = "用户A",
            userlogo = "",
            createtime = "01-15 10:30",
            replytotal = 5, // 更新回复总数
            agreenum = 5,
            replyList = mutableListOf(),
            parentId = null,
            replyToUserId = null,
            replyToUserName = null,
            isLiked = false,
            level = 0 // 主评论层级为0
        )
        
        val comment2 = CommentEntityItem(
            id = ++commentIdCounter,
            datatype = 0,
            itemid = itemid,
            content = "感谢分享，很有帮助",
            userid = 1002,
            nickname = "用户B",
            userlogo = "",
            createtime = "01-15 09:45",
            replytotal = 0,
            agreenum = 3,
            replyList = mutableListOf(),
            parentId = null,
            replyToUserId = null,
            replyToUserName = null,
            isLiked = false,
            level = 0 // 主评论层级为0
        )
        
        // 为第一个评论添加一级回复
        val reply1 = CommentEntityItem(
            id = ++commentIdCounter,
            datatype = 0,
            itemid = itemid,
            content = "同感，讲得很清楚",
            userid = 1003,
            nickname = "用户C",
            userlogo = "",
            createtime = "01-15 11:00",
            replytotal = 2, // 有两个回复
            agreenum = 1,
            replyList = mutableListOf(),
            parentId = comment1.id,
            replyToUserId = comment1.userid,
            replyToUserName = comment1.nickname,
            isLiked = false,
            level = 1, // 一级回复
            rootCommentId = comment1.id // 根评论ID
        )
        
        val reply2 = CommentEntityItem(
            id = ++commentIdCounter,
            datatype = 0,
            itemid = itemid,
            content = "请问还有其他相关的视频吗？",
            userid = 1004,
            nickname = "用户D",
            userlogo = "",
            createtime = "01-15 11:15",
            replytotal = 0,
            agreenum = 0,
            replyList = mutableListOf(),
            parentId = comment1.id,
            replyToUserId = comment1.userid,
            replyToUserName = comment1.nickname,
            isLiked = false,
            level = 1, // 一级回复
            rootCommentId = comment1.id // 根评论ID
        )
        
        // 为第一个回复添加二级回复
        val reply1_1 = CommentEntityItem(
            id = ++commentIdCounter,
            datatype = 0,
            itemid = itemid,
            content = "是的，讲解很详细",
            userid = 1005,
            nickname = "用户E",
            userlogo = "",
            createtime = "01-15 11:30",
            replytotal = 1, // 有一个回复
            agreenum = 2,
            replyList = mutableListOf(),
            parentId = reply1.id,
            replyToUserId = reply1.userid,
            replyToUserName = reply1.nickname,
            isLiked = false,
            level = 2, // 二级回复
            rootCommentId = comment1.id // 根评论ID
        )
        
        val reply1_2 = CommentEntityItem(
            id = ++commentIdCounter,
            datatype = 0,
            itemid = itemid,
            content = "我也觉得很棒",
            userid = 1006,
            nickname = "用户F",
            userlogo = "",
            createtime = "01-15 11:45",
            replytotal = 0,
            agreenum = 1,
            replyList = mutableListOf(),
            parentId = reply1.id,
            replyToUserId = reply1.userid,
            replyToUserName = reply1.nickname,
            isLiked = false,
            level = 2, // 二级回复
            rootCommentId = comment1.id // 根评论ID
        )
        
        // 为二级回复添加三级回复
        val reply1_1_1 = CommentEntityItem(
            id = ++commentIdCounter,
            datatype = 0,
            itemid = itemid,
            content = "希望能有更多这样的视频",
            userid = 1007,
            nickname = "用户G",
            userlogo = "",
            createtime = "01-15 12:00",
            replytotal = 0,
            agreenum = 0,
            replyList = mutableListOf(),
            parentId = reply1_1.id,
            replyToUserId = reply1_1.userid,
            replyToUserName = reply1_1.nickname,
            isLiked = false,
            level = 3, // 三级回复
            rootCommentId = comment1.id // 根评论ID
        )
        
        // 添加回复到各自的父评论
        reply1.replyList!!.addAll(listOf(reply1_1, reply1_2))
        reply1_1.replyList!!.add(reply1_1_1)
        comment1.replyList!!.addAll(listOf(reply1, reply2))
        
        sampleComments.addAll(listOf(comment1, comment2))
        
        localComments[itemid] = sampleComments
    }
    
    /**
     * 根据ID查找评论（递归查找）
     */
    private fun findCommentById(comments: List<CommentEntityItem>, commentId: Int): CommentEntityItem? {
        for (comment in comments) {
            if (comment.id == commentId) {
                return comment
            }
            // 递归查找回复中的评论
            comment.replyList?.let { replies ->
                val found = findCommentById(replies, commentId)
                if (found != null) return found
            }
        }
        return null
    }
    
    /**
     * 清空指定视频的评论数据
     */
    fun clearComments(itemid: String) {
        localComments.remove(itemid)
    }
    
    /**
     * 获取评论总数
     */
    fun getCommentCount(itemid: String): Int {
        val comments = localComments[itemid] ?: return 0
        var count = comments.size
        comments.forEach { comment ->
            count += comment.replyList?.size ?: 0
        }
        return count
    }
}
